<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const username = ref('')
const password = ref('')
const errorMessage = ref('')
const isLoading = ref(false)

const bgImages = [
  require('@/assets/login_bk_0.jpg'),
  require('@/assets/login_bk_1.jpg'),
  require('@/assets/login_bk_2.jpg'),
  require('@/assets/login_bk_3.jpg'),
  require('@/assets/login_bk_4.jpg'),
  require('@/assets/login_bk_5.jpg')
]

import { onMounted } from 'vue'

onMounted(() => {
  const randomIndex = Math.floor(Math.random() * bgImages.length)
  const loginContainer = document.querySelector('.login-container')
  loginContainer.style.backgroundImage = `url(${bgImages[randomIndex]})`
})

// 处理登录
const handleLogin = async () => {
  if (!username.value.trim() || !password.value.trim()) {
    errorMessage.value = '账号和密码不能为空'
    return
  }

  try {
    isLoading.value = true
    errorMessage.value = ''
    const response = await axios.post('http://localhost:8080/api/admin/login', {
      account: username.value,
      password: password.value
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    // 处理成功响应
    if (response.status === 200 && response.data.success) {
      localStorage.setItem('token', response.data.data.token)
      localStorage.setItem('username', response.data.data.user.username);
      localStorage.setItem('id', String(response.data.data.user.id));
      localStorage.setItem('account', response.data.data.user.account);
      await router.push('/dashboard')
    } else {
      errorMessage.value = '登录失败，请检查账号密码'
    }
  } catch (error) {
    // 处理错误
    if (error.response && error.response.data) {
      errorMessage.value = error.response.data.message || '登录失败，请检查账号密码'
    } else {
      console.error(error)
      errorMessage.value = '出现异常，请检查控制台'
    }
  } finally {
    isLoading.value = false
  }
}

// 监听回车键
const handleKeyup = (e) => {
  if (e.key === 'Enter' && !isLoading.value) {
    handleLogin()
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-card">
      <div class="logo-area">
        <h1>Smark 账本系统</h1>
        <p>管理员后台</p>
      </div>

      <form @submit.prevent="handleLogin" class="login-form">
        <div class="input-group">
          <label for="username">管理员账号</label>
          <input
              id="username"
              type="text"
              v-model="username"
              placeholder="请输入管理员账号"
              @keyup="handleKeyup"
          />
        </div>

        <div class="input-group">
          <label for="password">登录密码</label>
          <input
              id="password"
              type="password"
              v-model="password"
              placeholder="请输入登录密码"
              @keyup="handleKeyup"
          />
        </div>

        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>

        <button
            type="submit"
            :disabled="isLoading"
            :class="['login-btn', { loading: isLoading }]"
        >
          <span v-if="!isLoading">登录系统</span>
          <span v-else>登录中...</span>
        </button>
      </form>

      <div class="footer-note">
        <p>© 2025 Smark 账务管理系统 | 管理员版本</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-card {
  width: 100%;
  max-width: 420px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  padding: 40px 35px;
  transition: transform 0.3s ease;
}

.logo-area {
  text-align: center;
  margin-bottom: 35px;
}

.logo-area h1 {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.logo-area p {
  font-size: 15px;
  color: #7f8c8d;
}

.input-group {
  margin-bottom: 22px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #34495e;
  font-size: 14px;
}

input {
  width: 100%;
  padding: 14px 16px;
  border: 1px solid #e1e5eb;
  border-radius: 8px;
  font-size: 15px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.error-message {
  color: #e74c3c;
  font-size: 14px;
  margin-bottom: 15px;
  text-align: center;
  padding: 8px;
  background-color: rgba(231, 76, 60, 0.05);
  border-radius: 6px;
}

.login-btn {
  width: 100%;
  padding: 14px;
  background: linear-gradient(to right, #3498db, #2c80b9);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.login-btn:hover:not(:disabled) {
  background: linear-gradient(to right, #2c80b9, #2573a7);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.25);
}

.login-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.login-btn.loading {
  position: relative;
  color: transparent;
}

.login-btn.loading::after {
  content: "";
  position: absolute;
  width: 20px;
  height: 20px;
  top: 50%;
  left: 50%;
  margin: -10px 0 0 -10px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.footer-note {
  margin-top: 30px;
  text-align: center;
  color: #95a5a6;
  font-size: 13px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}
</style>